package com.app.utils.util.net;

import android.widget.ImageView;

import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageLoader.ImageListener;

/**
 * volley图片缓存管理类 获取ImageLoader对象
 * Created by xuxinghai on 2016/8/31.
 */
public class VollyImageCacheManager {

    private static String TAG = VollyImageCacheManager.class.getSimpleName();

    // 获取图片缓存类对象
    private static ImageLoader.ImageCache mImageCache = new VolleyImageCacheUtil();
    // 获取ImageLoader对象
    private static ImageLoader mImageLoader = new ImageLoader(NetUtils.getInstance().getRequestQueue(), mImageCache);

    /**
     * 获取ImageListener
     *
     * @param view
     * @param defaultImage
     * @param errorImage
     * @return
     */
    public static ImageLoader.ImageListener getImageListener(final ImageView view, final int defaultImage, final int errorImage) {

        return new ImageListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                // 回调失败
                if (errorImage != 0) {
                    view.setImageResource(errorImage);
                }
            }

            @Override
            public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
                // 回调成功
                if (response.getBitmap() != null) {
                    view.setImageBitmap(response.getBitmap());
                } else if (defaultImage != 0) {
                    view.setImageResource(defaultImage);
                }
            }
        };

    }

    /**
     * 提供给外部调用方法
     *
     * @param url
     * @param view
     */
    public static void loadImage(String url, ImageView view) {
        mImageLoader.get(url, getImageListener(view, 0,0), 0, 0);
    }

    /**
     * 提供给外部调用方法
     *
     * @param url
     * @param view
     * @param defaultImageResId
     * @param errorImageResId
     */
    public static void loadImage(String url, ImageView view, int defaultImageResId, int errorImageResId) {
        mImageLoader.get(url, getImageListener(view, defaultImageResId,errorImageResId), 0, 0);
    }

    /**
     * 提供给外部调用方法
     *
     * @param url
     * @param view
     * @param defaultImageResId
     * @param errorImageResId
     */
    public static void loadImage(String url, ImageView view, int defaultImageResId, int errorImageResId, int maxWidth, int maxHeight) {
        ImageLoader.ImageListener listener = ImageLoader.getImageListener(
                view, defaultImageResId,errorImageResId);
        //view.setImageResource(defaultImageResId);
        mImageLoader.get(url, listener, maxWidth, maxHeight);
    }
}
